<?php

namespace App\Http\Controllers\Admin\Framework\Common;

use App\Http\Controllers\Admin\ParentController;
use App\Master\Framework\Library\Uploads;
use App\Utils\AppResult;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class CommonController extends ParentController
{

    public function __construct(array $attributes = [])
    {
        parent::__construct();
    }

    /**
     * 获取第三方云上传token
     * @return string
     */
    public function uploadToken()
    {
        $res = (Uploads::getInstance('image'))->token()->getMessage();
        if ($res['code'] != 200){
            return AppResult::response201($res['msg'], $res['data']);
        }
        return AppResult::response200('success', $res['data']);
    }

    public function getFileKey()
    {
        $res = (Uploads::getInstance('image'))->getFileKey()->getMessage();
        return AppResult::response200('success', $res['data']);
    }

    /**
     * 公共接口，编辑器上传
     *
     * @param Request $request
     * @param string dir 文件类型 image，video，audio，file，media，flash
     * @return string
     */
    public function uploadEditor(Request $request)
    {
        $res = (Uploads::getInstance('image', [
            'suffix' => $request->suffix ?? 'jpg,png,bmp,jpeg,gif',
            'size'   => intval($request->size ?? 20)
        ]))->init()->getMessage();

        if ($res['code'] != 200) {
            return AppResult::response201($res['msg'], $res['data']);
        }

        return AppResult::response200($res['msg'], $res['data']);
    }

    /**
     * 图片上传
     *
     * @param Request $request
     * @return string|void
     */
    public function pictureUploads(Request $request)
    {
        $res = (Uploads::getInstance('image', [
            'suffix' => $request->suffix ?? 'jpg,png,bmp,jpeg,gif',
            'size'   => intval($request->size ?? 20)
        ]))->init()->getMessage();

        if ($res['code'] == 200) {
            return AppResult::response200($res['msg'], $res['data']);
        } else {
            abort(500, $res['msg']);
        }
    }

    /**
     * 公共接口，文件上传
     *
     * @param Request $request
     * @param string suffix 文件后缀
     * @param string size 文件限制大小
     * @return string|void
     */
    public function fileUploads(Request $request)
    {
        $res = (Uploads::getInstance('file', [
            'suffix' => $request->suffix ?? 'pdf,doc,docx,xls,xlsx,xlsm,xlt,xltx,xltm,csv',
            'size'   => intval($request->size ?? 20)
        ]))->init()->getMessage();
        if ($res['code'] == 200) {
            return AppResult::response200($res['msg'], $res['data']);
        } else {
            abort(500, $res['msg']);
        }
    }

    /**
     * 清除缓存
     * @return string
     */
    public function cacheClear()
    {
        Cache::clear();
        return AppResult::response200('操作成功！');
    }
}